import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
} from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './TableList.less';

Date.prototype.Format = function (fmt) { //author: meizz
  var o = {
    "Y+": this.getUTCFullYear(),
    "M+": this.getMonth() + 1, //月份
    "D+": this.getDate(), //日
    "H+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
  if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = ['default','success', 'error'];
const status = ['未检查', '正常', 'cookie失效'];

const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleAdd, handleModalVisible,updateAccount } = props;
  console.log("updateAccount:",updateAccount)
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleAdd(updateAccount,fieldsValue);
    });
  };


  return (
    <Modal
      title="更新Cookie"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="Cookie">
        {form.getFieldDecorator('cookie', {
          rules: [{ required: true, message: 'Please input some Cookie...' }],
        })(<Input placeholder="请输入" />)}
      </FormItem>
    </Modal>
  );
});

@connect(({ rule, loading }) => ({
  rule,
  loading: loading.models.rule,
}))
@Form.create()
export default class TableList extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},

    updateAccount:{},
    updateVisible: false,
  };

  componentDidMount() {
    this.refresh()
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      page: pagination.current,
      size: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'rule/fetchAccounts',
      payload: params,
    });
  };


  refresh = () => {
    const { dispatch } = this.props;
    const { rule: { accounts:{ list, page,page_size }}} = this.props;

    dispatch({
      type: 'rule/fetchAccounts',
      payload: {
        page:page,
        size:page_size,
      },
    });
  }

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'rule/fetchAccounts',
        payload: values,
      });
    });
  };



  renderForm() {
    return this.state.expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  handleChange = value => {
    console.log(`selected ${value}`);
    if (value == 'all'){
      this.state.type = ""
    } else{
      this.state.type = value
    }
    this.refresh()
  }
  
  praseType = value => {
    switch(value){
      case 'BAIJIA':
        return "百家"
      case 'TOUTIAO':
        return "头条"
      case 'QIER':
        return "企鹅"
      case 'DAYU':
        return "大鱼"
    }
  }
  
  praseDate = value => {
    var date = new Date(value)
    date.setHours(date.getHours()-8)
    var s = date.Format('YYYY-MM-DD HH:mm:ss')
    return s
  }

  handleUpdateVisible = (flag,account) => {
    this.setState({
      updateAccount:account,
      updateVisible: !!flag,
    });
  }

  handleUpdate = (account,fields) => {
    console.log("fields:",fields)

    this.props.dispatch({
      type: 'rule/updateCookie',
      payload: {
        id: account.id,
        cookie:fields.cookie,
      },
      callback: () => {
        message.success('更新成功');
        this.refresh()
      }
    })

    console.log("fields:",fields)
      this.setState({
      updateVisible: false,
    });
  }

  render() {
    // praseType = this.praseType
    const { rule: { accounts }, loading } = this.props;
    const { selectedRows, updateVisible,updateAccount } = this.state;

    const columns = [
      {
        title: '编号',
        dataIndex: 'id',
      },
      {
        title: '名称',
        dataIndex: 'nick_name',
        render: (val,record) => <span>{record.nick_name}</span>,
      },
      {
        title: '平台',
        dataIndex: 'plat',
        filters: [
          {
            text: '百家',
            value: '百家',
          },
          {
            text: '头条',
            value: '头条',
          },
          {
            text: '企鹅',
            value: '企鹅',
          },
          {
            text: '大鱼',
            value: '大鱼',
          },
        ],
        onFilter: (value, record) => this.praseType(record.plat) === value,
        render: (val,record) => <span>{this.praseType(record.plat)}</span>,
      },
      {
        title: 'username',
        dataIndex: 'username',
        render: val => <span>{val}</span>,
      },
      {
        title: '状态',
        dataIndex: 'status',
        filters: [
          {
            text: status[0],
            value: 0,
          },
          {
            text: status[1],
            value: 1,
          },
          {
            text: status[2],
            value: 2,
          },
        ],
        onFilter: (value, record) => record.status.toString() === value,
        render(val) {
          return <Badge status={statusMap[val]} text={status[val]} />;
        },
      },
      {
        title: '操作',  
        render: (val , record) => (
          <span>
            <a onClick={()=> this.handleUpdateVisible(true,record)}>更新Cookie</a>  
            {/* <Divider type="vertical" /> */}
            {/* <a onClick={()=> this.handleUpdateVisible(true,record)}>更新Cookie</a>   */}
          </span>
        ),
      },
    ];

    const parentMethods = {
      handleAdd : this.handleUpdate,
      handleModalVisible: this.handleUpdateVisible,
      updateAccount : updateAccount,
    };

    return (
      <div style={{ margin: '0 -46px 0' }}>
        <Card bordered={false}>
          <div className={styles.tableList}>

            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={accounts}
              columns={columns}
              pagination={false}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <CreateForm {...parentMethods} modalVisible={updateVisible} />
      </div>
    );
  }
}
